package io.github.wanggit.antrpc.console.web.dto;

import io.github.wanggit.antrpc.console.web.utils.TimeFormatUtil;
import lombok.Data;
import org.joda.time.DateTime;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

@Data
public class TimeRangeDTO implements Serializable {

    private static final long serialVersionUID = -3545902796401516160L;

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";

    private String start;

    private String end;

    private String range;

    public static TimeRangeDTO buildOf(String ranges) {
        if (null != ranges) {
            TimeRangeDTO timeRangeDTO = new TimeRangeDTO();
            timeRangeDTO.setRange(ranges);
            String[] tmps = ranges.split("~");
            Date startDate = TimeFormatUtil.checkAndConvert(tmps[0]);
            Date endDate = TimeFormatUtil.checkAndConvert(tmps[1]);
            if (null != startDate && null != endDate) {
                timeRangeDTO.setStart(startDate.toInstant().toString());
                timeRangeDTO.setEnd(endDate.toInstant().toString());
                return timeRangeDTO;
            }
        }
        DateTime standard = new DateTime();
        Date endDate = standard.toDate();
        Date startDate = standard.minusHours(1).toDate();
        TimeRangeDTO timeRangeDTO = new TimeRangeDTO();
        timeRangeDTO.setRange(
                new SimpleDateFormat(DATE_FORMAT).format(startDate)
                        + "~"
                        + new SimpleDateFormat(DATE_FORMAT).format(endDate));
        timeRangeDTO.setStart(startDate.toInstant().toString());
        timeRangeDTO.setEnd(endDate.toInstant().toString());
        return timeRangeDTO;
    }
}
